package com.javaweb.dao.impl;

import com.javaweb.aop.NPECatch;
import com.javaweb.dao.PermDao;
import com.javaweb.model.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/24 22:43
 */

/**
 * todo: 实现全部如下方法
 */
@Repository
@Slf4j
public class PermDaoImpl implements PermDao {
    @Autowired
    private Connection conn;

    @Override
    @NPECatch
    public Integer insert(Permission perm) {
        String sql = "INSERT INTO tb_permission (name, url) VALUES (?, ?)";
        try (PreparedStatement ps = this.conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, perm.getName());
            ps.setString(2, perm.getUrl());
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        return generatedKeys.getInt(1);
                    }
                }
            }
        } catch (SQLException e) {
            log.error("execute insert permission error: " + e.getMessage(), e);
        }
        return 0;
    }

    @Override
    @NPECatch
    public Integer insertRolePerm(int roleId, int permId) {
        String sql = "INSERT INTO tb_role_per (role_id, per_id) VALUES (?, ?)";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, roleId);
            ps.setInt(2, permId);
            return ps.executeUpdate();
        } catch (SQLException e) {
            log.error("execute insertRolePerm error: " + e.getMessage());
        }
        return 0;
    }

    @Override
    @NPECatch
    public Permission selectOne(String name, String url) {
        String sql = "SELECT * FROM tb_permission WHERE name = ? AND url = ?";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, url);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Permission()
                        .setPerId(rs.getInt(1))
                        .setName(rs.getString(2))
                        .setUrl(rs.getString(3));
            }
        } catch (SQLException e) {
            log.error("execute selectOne error: " + e.getMessage());
        }
        return null;
    }

    @Override
    @NPECatch
    public Permission selectOneById(int permId) {
        String sql = "SELECT * FROM tb_permission WHERE per_id = ?";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, permId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Permission()
                        .setPerId(rs.getInt(1))
                        .setName(rs.getString(2))
                        .setUrl(rs.getString(3));
            }
        } catch (SQLException e) {
            log.error("execute selectOneById error: " + e.getMessage());
        }
        return null;
    }

    @Override
    @NPECatch
    public List<Permission> selectPermsByRoleName(String roleName) {
        String sql = "SELECT p.* FROM tb_permission p " +
                "JOIN tb_role_per rp ON p.per_id = rp.per_id " +
                "JOIN tb_role r ON r.role_id = rp.role_id " +
                "WHERE r.name = ?";
        List<Permission> permissions = new ArrayList<>();
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setString(1, roleName);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                permissions.add(new Permission()
                        .setPerId(rs.getInt(1))
                        .setName(rs.getString(2))
                        .setUrl(rs.getString(3)));
            }
        } catch (SQLException e) {
            log.error("execute selectPermsByRoleName error: " + e.getMessage());
        }
        return permissions;
    }

    @Override
    @NPECatch
    public List<Permission> selectPermsByRoleId(int roleId) {
        String sql = "SELECT p.* FROM tb_permission p " +
                "JOIN tb_role_per rp ON p.per_id = rp.per_id " +
                "WHERE rp.role_id = ?";
        List<Permission> permissions = new ArrayList<>();
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, roleId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                permissions.add(new Permission()
                        .setPerId(rs.getInt(1))
                        .setName(rs.getString(2))
                        .setUrl(rs.getString(3)));
            }
        } catch (SQLException e) {
            log.error("execute selectPermsByRoleId error: " + e.getMessage());
        }
        return permissions;
    }

    @Override
    @NPECatch
    public Integer deleteById(int permId) {
        String sql = "DELETE FROM tb_permission WHERE per_id = ?";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, permId);
            return ps.executeUpdate();
        } catch (SQLException e) {
            log.error("execute deleteById error: " + e.getMessage());
        }
        return 0;
    }
}
